local filename = "turntable.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
local redisdao = require "redisdao"
local base = require "base"
require "pubenum"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local service = nil
local CMD = {
	service = nil
}

--奖励id
local PRIZE_ID = {
    FANGKA = 1,     --房卡
    DIAMOND = 2,    --金豆
    COIN = 3,       --金币
}

--奖励名
local PRIZE_NAME = {
    [PRIZE_ID.FANGKA] = "fangka",     --房卡
    [PRIZE_ID.DIAMOND] = "diamond",   --金豆
    [PRIZE_ID.COIN] = "coin",         --金币
}

--
--获得连续登陆奖励
--
local function get_loginprize(rid, response)
    local loginrecord = nil
    local is_loginprize = false
    local continuous_days = 1
    local turntable_times = 1
    local cur_time = timetool.get_time()

    --判断是否有连续登陆奖励
    local result, data = redisdao.query_data(".gmmqredis", "get", rid .. ":loginrecord")
    if result and data then
        loginrecord = json.decode(data)
        if loginrecord then
            local cur_day = os.date("%d",cur_time)
            local last_day = os.date("%d",loginrecord.last_logintime)
            local dur_time = cur_time - loginrecord.last_logintime
            local oneday_time = 48 * 3600
            if dur_time >= 0 and dur_time < oneday_time then  --相邻2天内
                if cur_day ~= last_day then
                    continuous_days = continuous_days + loginrecord.continuous_days
                    is_loginprize = true
                else
                    continuous_days = loginrecord.continuous_days
                    turntable_times = turntable_times + loginrecord.turntable_times
                end
            end
        end
    end

    --更新登录记录
    loginrecord = loginrecord or { }
    loginrecord.last_logintime = cur_time
    loginrecord.continuous_days = continuous_days
    loginrecord.turntable_times = turntable_times

    --获得连续登陆奖励列表
    if is_loginprize then
        result, data = redisdao.query_data(".gmmqredis", "get", "login_prize_list")
        if not result or not data then
            loginprize_list = {}
        else
            loginprize_list = json.decode(data) or {}
        end  
        for k,item in pairs(loginprize_list) do
            if item.days then
                if item.days == continuous_days then
                    response.loginprize_id = item.id
                    response.loginprize_value = tonumber(item.value)
                    response.login_prizeitem_id = k
                    break
                end
            elseif item.max_days and continuous_days >= item.max_days then
                response.loginprize_id = item.id
                response.loginprize_value = tonumber(item.value)
                response.login_prizeitem_id = k
                break
           end
        end

        --修改数据
        if response.loginprize_id then
            local itemvalues = { }
            local prizename = PRIZE_NAME[response.loginprize_id]
            local begin = service.money[prizename] or 0
            itemvalues[prizename] =  response.loginprize_value

            --记录日志
            local logstr = nil
            local logname = nil
            local xx = "nil"
            local value = response.loginprize_value
            if response.loginprize_id == PRIZE_ID.FANGKA then
                logstr = string.format("%d,%d,%s,%d,%d,%d", EFangKaChange.LOGINPRIZEFANGKA, rid, xx, value, begin, service.money.fangka)
                logname = ".fangkalog"
            elseif response.loginprize_id == PRIZE_ID.DIAMOND then
                logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s", EDiamondChange.LOGINPRIZE, rid, service.info.level, value, 0, 0, begin, service.money.diamond, service.money.lock_diamond, xx, xx)
                logname = ".diamondlog"
            elseif response.loginprize_id == PRIZE_ID.COIN then
                logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s", ECoinChange.LOGINPRIZE, rid, service.info.level, value, 0, 0, begin, service.money.coin, service.money.lock_coin, xx, xx)
                logname = ".coinlog"
            end

            return true,loginrecord,itemvalues,logname,logstr
       end
    end

    return true,loginrecord
end

--
--转盘
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
    msgbody = msgbody or {}

    local response = { }

    --获得连续登陆奖励
    local is_ok,loginrecord,changeitems,logname,logdata = get_loginprize(rid, response)
    if not is_ok then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "获取奖励失败"}
    end

    --检测转盘次数
    local is_free = true
    local cost_item = nil
    local result, data = redisdao.query_data(".gmmqredis", "get", "turntable_config")
    local turntable_config = nil
    if result and data then
        turntable_config = json.decode(data)
    end
    turntable_config = turntable_config or {max_times = 4, cost_list = {}, free_times = 1}
    if loginrecord.turntable_times > turntable_config.max_times then
        return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "已超过当天可转动次数上限"} 
    elseif loginrecord.turntable_times > turntable_config.free_times then --超过1次，要消耗金豆
        is_free = false
        
        --检测道具是否足够
        local more_times = loginrecord.turntable_times - turntable_config.free_times
        cost_item = turntable_config.cost_list[more_times] or {prop_id = 2, cost = 100}
        local name = PRIZE_NAME[cost_item.prop_id]
        local prop_num = service.money[name] or 0
        if prop_num < cost_item.cost then
            return {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "金豆数量不足"} 
        end
    end

    --获得转盘奖励列表
    result, data = redisdao.query_data(".gmmqredis", "get", "turntable_prize_list")
    local tableprize_list = nil
    if not result or not data then
        tableprize_list = {}
    else
        tableprize_list = json.decode(data) or {}
    end

    --获得随机数
    local rand_num = base.get_random(1,1000)

    --获得转盘奖励
    local beginvalue = 0
    for k,item in pairs(tableprize_list) do
        local v = math.floor(item.prob * 1000)
        local endvalue = beginvalue + v
        if rand_num > beginvalue and rand_num <= endvalue then
            response.id = item.id
            response.value = tonumber(item.value)
            response.table_prizeitem_id = k
            break
        end
        beginvalue = endvalue
    end

    --修改数据
    is_ok = false
    if response.id and PRIZE_NAME[response.id] then
        local itemvalues = { }
        local prizename = PRIZE_NAME[response.id]
        local begin = service.money[prizename] or 0

        changeitems = changeitems or { }
        itemvalues[prizename] = { }
        itemvalues[prizename].begin = begin
        itemvalues[prizename].value = response.value
        changeitems[prizename] = (changeitems[prizename] or 0) + response.value
        if not is_free then
            local name = PRIZE_NAME[cost_item.prop_id]
            changeitems[name] = (changeitems[name] or 0) - cost_item.cost
            itemvalues[name] = itemvalues[name] or { }
            itemvalues[name].begin = service.money[name]
            itemvalues[name].value = (itemvalues[name].value or 0) - cost_item.cost
        end

        local setargs = service:change_money(changeitems)
	    if setargs then
            --记录日志
            for key,item in pairs(itemvalues) do
                local logstr = nil
                local comment = { }
                local now = timetool.get_time()
                comment.tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
                comment.table_uuid = "turnnode" .. "_" .. 0 .. "_" .. 0 .. "_" .. now
                if key == "fangka" then
                    logstr = string.format("%d,%d,%s,%d,%d,%d", EFangKaChange.TRUNTABLEFANGKA, rid, xx, item.value, item.begin, service.money.fangka)
                    skynet.send(".fangkalog", "lua", "write", logstr)
                elseif key == "diamond" then
                    logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.TRUNTABLE, rid, service.info.level, item.value, 0, 0, item.begin, service.money.diamond, service.money.lock_diamond, comment.table_uuid, now, comment.tradeid)
                    if item.value < 0 then
                        skynet.send(".diamondlog", "lua", "write_file_redis", logstr, rid)
                    else
                        skynet.send(".diamondlog", "lua", "wrie", logstr)
                    end
                elseif key == "coin" then
                    logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", ECoinChange.TRUNTABLE, rid, service.info.level, item.value, 0, 0, item.begin, service.money.coin, service.money.lock_coin, comment.table_uuid, now, comment.tradeid)
                    skynet.send(".coinlog", "lua", "write", logstr)
                end
            end
            
            if logname and logdata then
                skynet.send(logname, "lua", "write", logdata)
            end
            is_ok = true
        end
    end
    
    if not is_ok then
        loginrecord.turntable_times = loginrecord.turntable_times - 1
        response = {retcode = EErrCode.ERR_INVALID_REQUEST,retstr = "获取奖励失败"}
    end
   
    --保存登录记录
    redisdao.query_data(".gmmqredis", "set", rid .. ":loginrecord",json.encode(loginrecord))

	return response
end

return CMD
